<template>
  <div class="cont">
    <div class="mode-title">{{ modeTitle }}</div>
    <div class="form-title"><span class="line"></span>基础信息：</div>
    <el-form label-position="right" ref="formData" :rules="rules" :model="formData" label-width="80px">
      <el-form-item label="购货单位" prop="company">
        <el-input v-model="formData.company"></el-input>
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker v-model="formData.date" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期"
          size="small" />
      </el-form-item>
    </el-form>
    <div class="action">
      <div class="action-title"><span class="line"></span>购货信息：</div>
      <div class="right">
        <div class="add-info" v-if="mode == 'edit'" @click="handlePrintShow">打印预览</div>
        <!-- <div class="add-pay" @click="handleAddPay">添加其他信息</div> -->
      </div>
    </div>
    <el-table v-loading="isLoading" border :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
      :data="tableData" show-summary :summary-method="getSummaries" align="left" header-align="left"
      style="width: 100%">
      <el-table-column v-for="(item, index) in columnList" :prop="item.prop" :label="item.label" :width="item.width">
        <template slot-scope=" scope">
          <template v-if="item.prop == 'type'">
            <el-select v-model="scope.row['type']" placeholder="请选择单子类型" @change="handleTypeChange(scope.row)"
              style="width: 260px">
              <el-option :label="item.label" :value="item.val" v-for="item in typeList" />
            </el-select>
          </template>
          <template v-if="item.prop == 'remark'">
            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 10 }" v-model="scope.row['remark']"
              @change="onChange(scope.row)" />
          </template>
          <template v-if="item.prop == 'name'">
            <el-input v-model="scope.row['name']" @change="onChange(scope.row)" />
          </template>
          <template v-if="scope.row['type'] == 3">
            <template v-if="item.prop == 'size'">
              <el-input maxLength='9' v-model="scope.row['width']" @change="onChange(scope.row, 'width')" />
              <div class="" style="margin: 0 10px">X</div>
              <el-input maxLength='9' v-model="scope.row['height']" @change="onChange(scope.row, 'height')" />
            </template>
            <template v-if="item.prop == 'area' && scope.row['type'] == 1">
              <span>{{ scope.row['area'] }}</span>
            </template>
            <template v-if="item.prop == 'sets'">
              <el-input maxLength='9' v-model="scope.row['sets']" @change="onChange(scope.row, 'sets')" />
            </template>
            <template v-if="item.prop == 'price'">
              <el-input maxLength='9' v-model="scope.row['price']" @change="onChange(scope.row, 'price')" />
            </template>
            <template v-if="item.prop == 'total'">
              <el-input v-model="scope.row['total']" @change="onChange(scope.row, 'total')" />
            </template>
          </template>
          <template v-else>
            <template v-if="item.prop == 'size'">
              <el-input maxLength='9'
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+13)}"
                v-model="scope.row['width']" @change="onChange(scope.row, 'width')" />
              <div class="" style="margin: 0 10px">X</div>
              <el-input maxLength='9'
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+13)}"
                v-model="scope.row['height']" @change="onChange(scope.row,'height')" />
            </template>
            <template v-if="item.prop == 'area' && scope.row['type'] == 1">
              <span>{{ scope.row['area']}}</span>
            </template>
            <template v-if="item.prop == 'sets'">
              <el-input maxLength='9'
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+13)}"
                v-model="scope.row['sets']" @change="onChange(scope.row, 'sets')" />
            </template>
            <template v-if="item.prop == 'price'">
              <el-input maxLength='9'
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+13)}"
                v-model="scope.row['price']" @change="onChange(scope.row, 'price')" />
            </template>
            <template v-if="item.prop == 'total'">
              <span>{{ scope.row['total']}}</span>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="submit">
      <el-button type="primary" @click="onSubmit">提交</el-button>
    </div>
    <el-dialog title="" :visible.sync="isShowPrint" append-to-body @close='handlePrintClose'>
      <div id="printArea">
        <section class="pdf-content">
          <div class="print-title">利兴门业销货单</div>
          <div class="print-hd">
            <div class="item">
              <div class="label">购货单位：</div>
              <div class="val">{{ formData.company }}</div>
            </div>
            <div class="item">
              <div class="label">日期：</div>
              <div class="val">{{ formData.date }}</div>
            </div>
          </div>
          <div class="print-hd print-orderNo">
            <div class="item">
              <div class="label">订单号：</div>
              <div class="val">{{ formData.orderNo }}</div>
            </div>
            <div class="item">
              <div class="label"></div>
              <div class="val"></div>
            </div>
          </div>
          <div class="print-table">
            <el-table id="printTable" border :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
              :data="tableData" show-summary :summary-method="getSummaries" align="center" header-align="left"
              style="width: 100%">
              <el-table-column v-for="(item, index) in columnList2" :prop="item.prop" :label="item.label"
                :width="item.width">
                <template slot-scope="scope">
                  <template v-if="item.prop == 'size'">
                    <div class="text" v-if="scope.row['width']">{{scope.row['width']}}</div>
                    <div style="margin: 0 4px" v-if="scope.row['width'] || scope.row['height']">X
                    </div>
                    <div class="text" v-if="scope.row['height']">{{scope.row['height']}}</div>
                  </template>
                  <template v-else>
                    <template v-if="item.prop == 'remark'">
                      <div class="text">{{ scope.row[item.prop] }}</div>
                    </template>
                    <template v-else>
                      <template v-if="item.prop == 'area'">
                        <div class="text" v-if="scope.row['type'] == 1">{{ scope.row['area'] }}</div>
                      </template>
                      <div class="text" v-else>{{ scope.row[item.prop] || '' }}</div>
                    </template>
                  </template>
                </template>
              </el-table-column>
            </el-table>
            <div class="print-foot">
              <div class="item" v-for="item in footInfo" :key="item.id">
                <div class="label">{{ item.label }}：</div>
                <div class="val">{{ item.val }}</div>
              </div>
            </div>
          </div>
        </section>
      </div>
      <div class="print-button" v-print="print">打印</div>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name: "Order",
    data() {
        return {
          mode: '',
          modeTitle: '',
          formData: {
            company: '',
            date: ''
          },
          isLoading: false,
          tableData: [],
          columnList: [
            {
              prop: 'type',
              label: '类型',
              width: 160,
            },
            {
              prop: 'name',
              label: '名称',
              width: 140,
            },
            {
              prop: 'size',
              label: '尺寸',
              width: 180,
            },
            {
              prop: 'area',
              label: '数量',
              width: 100,
            },
            {
              prop: 'sets',
              label: '套数',
              width: 100,
            },
            {
              prop: 'price',
              label: '单价',
              width: 100,
            },
            {
              prop: 'total',
              label: '金额',
              width: 120,
            },
            {
              prop: 'remark',
              label: '备注',
              width: '',
            },
          ],
          columnList2: [
            {
              prop: 'name',
              label: '名称',
              width: 80,
            },
            {
              prop: 'size',
              label: '尺寸',
              width: 110,
            },
            {
              prop: 'area',
              label: '数量',
              width: 60,
            },
            {
              prop: 'sets',
              label: '套数',
              width: 50,
            },
            {
              prop: 'price',
              label: '单价',
              width: 60,
            },
            {
              prop: 'total',
              label: '金额',
              width: 70,
            },
            {
              prop: 'remark',
              label: '备注',
              width: 160,
            },
          ],
          typeList: [
            {
              val: 1,
              label: '计算面积'
            },
            {
              val: 2,
              label: '不计算面积'
            },
            {
              val: 3,
              label: '其他'
            }
          ],
          rules: {
            company: [
                  {
                      required: true,
                      message: "请输入购货单位",
                      trigger: "blur",
                  },
              ],
              date: [
                  { required: true, message: "请输入日期", trigger: "blur" },
              ]
          },
          balanceMoney: 0,
          footInfo: [
            {
              id: 1,
              label: '生产经营',
              val: '工业提升门、工业平开门、工业平移门、翻板车库门、欧式保温门、抗风卷帘门'
            },
            {
              id: 2,
              label: '地址',
              val: '河北省任丘市辛中驿镇铁路桥北200米路东'
            },
            {
              id: 3,
              label: '电话',
              val: '0317-2926576 2927576'
            },
            {
              id: 4,
              label: '手机',
              val: '18632760200 18503173323'
            }
          ],
          isShowPrint: false,
          print: {
            id: 'printArea',
            popTitle: '配置页眉标题', // 打印配置页上方的标题
            extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
            preview: false, // 是否启动预览模式，默认是false
            previewTitle: '预览的标题', // 打印预览的标题
            previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
            zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
            previewBeforeOpenCallback () { console.log('正在加载预览窗口！')}, // 预览窗口打开之前的callback
            previewOpenCallback () { 
              setTimeout(() => {
                this.isShowPrint = false
              }, 100)
              console.log('已经加载完预览窗口，预览打开了！') 
            }, // 预览窗口打开时的callback
            beforeOpenCallback () { console.log('开始打印之前！') }, // 开始打印之前的callback
            openCallback () { console.log('执行打印了！') }, // 调用打印时的callback
            closeCallback () {
              // this.$router.push({ path: '/OrderForm', query: { id: this.$route.query.id } })
              console.log('关闭了打印工具！', this) 
            }, // 关闭打印的callback(无法区分确认or取消)
            clickMounted () { console.log('点击v-print绑定的按钮了！') },
            // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
            // asyncUrl (reslove) {
            //   setTimeout(() => {
            //     reslove('http://localhost:8080/')
            //   }, 2000)
            // },
            standard: '',
            extarCss: ''
          },
        };
    },
  components: {
    },
    computed: {
    },
    mounted() {
      console.log(this.$route.query)
      this.mode = this.$route.query.id ? 'edit' : 'add'
      this.modeTitle = this.$route.query.id ? '编辑表单' : '新增表单'
      if (this.$route.query.id) {
        // 编辑
        this.getData(this.$route.query.id)
      } else {
        this.tableData = [
          {
            id: 1,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },
          {
            id: 2,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 3,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 4,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 5,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 6,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 7,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 8,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 9,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          },{
            id: 10,
            type: '',
            name: '',
            width: '',
            height: '',
            area: '',
            sets: '',
            price: '',
            total: '',
            remark: ''
          }
        ]
      }
    },
    methods: {
      handlePrintShow() {
        this.isShowPrint = true
      },
      handlePrintClose() {
        this.closeDialog = false
      },
      // 回显数据
      async getData(id) {
        this.isLoading = true
        this.$axios.get(this.$httpUrl + `/order/${id}`).then(res => res.data).then((res) => {
          if (res.code == 200) {
            this.formData = {
              company: res.data.company,
              date: res.data.date,
              orderNo: res.data.orderNo
            }
            res.data.materials.forEach(e => {
              if(!e.type) {
                e.total = ''
              }
            })
            // 表格
            this.tableData = res.data.materials
            // 总额
            this.balanceMoney = res.data.balanceMoney
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败...",
            });
          }
        });
        this.isLoading = false
      },
      // handleAddInfo() {
      //   // 
      // },
      // handleAddPay() {
      //   //
      // },width
      // 类型变化
      handleTypeChange(row) {
        row.width = ''
        row.height = ''
        row.area = ''
        row.sets = ''
        row.price = ''
        row.total = ''
      },
      // 输入框失改变
      onChange(row, type) {
        if (!row.type) {
          return
        }
        if (row.type == 3) {
          row.total = row.total && parseInt(row.total)
          return
        }
        // 其他
        // if (row.type == 3) {
        //   row.width = 0
        //   row.height = 0
        //   row.area = 0
        //   row.sets = 0
        //   row.price = 0
        //   row.total = 0
        //   row.total = 0
        //   // 
        row.total = parseInt(row.total)
        //   return
        // }
        // 尺寸
        if (type == 'width' || type == 'height') {
          // 计算面积
          
          if (row.type == 1) {
            const area = row.width * row.height
            row.area = area.toFixed(2)
            const num = row.price * row.sets * area
            row.total = parseInt(num)
          }
        }
        // 单价
        if (type == 'price') {
          if (row.type == 1) {
            const num = row.price * row.sets * row.area
            row.total = parseInt(num)
          } else {
            const num = row.price * row.sets
            row.total = parseInt(num)
          }
        }
        // 套数
        if (type == 'sets') {
          if (row.type == 1) {
            const num = row.price * row.sets * row.area
             row.total = parseInt(num)
          } else {
            const num = row.price * row.sets
            row.total = parseInt(num)
          }
        }
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (column.property == 'total') {
            const values = data.map((item) => {
              return Number(item[column.property])
            })
            // const values = valuesMap.filter(e => e)
            console.log('2',data, values)
            if (!values.every((value) => Number.isNaN(value))) {
              const sumItemVal = `${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)}`
              const balanceMoney = parseInt(Number(sumItemVal))
              sums[index] = balanceMoney
              this.balanceMoney = balanceMoney
            } else {
              sums[index] = 'N/A'
            }
          } else {
            sums[index] = ''
          }
          
        })

        return sums
      },
      // 新增提交
      onSubmitForAdd(parmas) {
        // 发出请求
        this.$axios.post(this.$httpUrl + "/order", parmas).then(res => res.data).then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "新增成功！",
            });
            this.$router.push({ path: '/Order' })
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败...",
            });
          }
        });
      },
      // 编辑提交
      onSubmitForEdit(parmas) {
        parmas.id = this.$route.query.id
        // 发出请求
        this.$axios.put(this.$httpUrl + "/order", parmas).then(res => res.data).then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "编辑成功！",
            });
            this.$router.push({ path: '/Order' })
            // this.tableData = res.data.records;
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败...",
            });
          }
        });
      },
      // 提交
      onSubmit() {
        this.$refs['formData'].validate((valid) => {
          if (valid) {
           const arrs = this.tableData.filter(e => {
            return e.type
           })
           if (arrs.length) {
             let receiveMoney = 0
             let totalMoney = 0
             this.tableData.forEach(e=> {
                if (e.type == 3) {
                  if (e.total < 0) {
                    receiveMoney += Number(e.total)
                    debugger
                  } else {
                    totalMoney += Number(e.total)
                  }
                } else {
                  totalMoney += Number(e.total)
                }
             })
            const parmas = {
              ...this.formData,
              materials: this.tableData,
              balanceMoney: Number(this.balanceMoney),
              receiveMoney: receiveMoney,
              totalMoney
            }
            console.log('parmas请求参数',parmas)
             if (this.mode == 'add') {
              // 新增
               this.onSubmitForAdd(parmas)
             } else {
               this.onSubmitForEdit(parmas)
             }
           } else {
            this.$message({
                type: "error",
                message: "请填写完整购货信息",
            });
           }
          } else {
            
          }
        })
      }
    }
};
</script>

<style scoped>
.cont {
  marign: 20px;
  padding: 20px 40px;
}
.mode-title {
  font-size: 24px;
  font-weight: 500;
  margin-left: -20px;
}
.el-form {
  display: flex;
  width: 600px;
}

>>> .el-table__cell .cell {
    display: flex;
    align-items: center;
}
.form-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  margin: 30px 0 20px;
}
.action {
  display: flex;
  align-items: center;
  margin: 20px 0 20px;
}
.action .action-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  width: 100px;
}
.action .right {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}
.action .right .add-info {
  font-size: 12px;
  font-wight: 500;
  margin-right: 20px;
  /* border: 1px solid #409EFF; */
  background-color: #409EFF;
  color: #fff;
  padding: 8px 14px;
  border-radius: 10px;
}
.action .right .add-pay {
  font-size: 12px;
  font-wight: 500;
  /* border: 1px solid #409EFF; */
  background-color: #409EFF;
  color: #fff;
  padding: 8px 10px;
  border-radius: 10px;
}
.form-title .line {
  display: inline-block;
  width: 4px;
  height: 14px;
  margin: 4px;
  background-color: #409EFF;
}
.submit {
  margin: 10px 10px;
  text-align: right;
}


.pdf-content {
  padding: 10px 0;
  text-align: center;
}
.print-title {
  font-weight: 500;
  font-size: 24px;
  margin: 20px 40px 20px;
  text-align: center;
}

.print-hd {
  margin: 0px 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.print-orderNo {
  margin: 0 10px;
}
.print-hd .item {
  display: flex;
  margin: 10px 0;
  font-size: 14px;
  justify-content: flex-start;
}

.print-hd .label {
  width: 100px;
  font-size: 16px;
  font-weight: 500;
}

.print-table {
  table-layout: auto !important;
  padding: 10px 20px;
}
.print-table>>>.el-table__body td.el-table__cell {
  line-height: 34px!important;
  height: 34px!important;
}
.print-table .text {
  font-size: 14px;
  /* font-weight: 500; */
}
.print-table>>>.cell {
  font-weight: 500;
}
.print-table .cont-table .tr {
  display: flex;
  justify-content: space-between;
}
.print-table .cont-table .tr .td {
  flex: 1;
  text-align: center;
  border: 1px solid #ebeef5;
  padding: 5px;
  font-weight: 600;
  color: #333;
}

.print-foot {
  margin: 40px 0 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.print-foot .item {
  width: 600px;
  display: flex;
  margin: 4px 0;
  font-size: 14px;
  justify-content: flex-start;
}
.print-foot .label {
  width: 80px;
  font-size: 16px;
  font-weight: 500;
  text-align: left;
}
.print-foot .val {
  flex: 1;
  text-align: left;
}
.print-button {
  font-size: 12px;
  font-wight: 500;
  background-color: #409EFF;
  color: #fff;
  padding: 8px 14px;
  border-radius: 10px;
  width: 60px;
  margin: 30px auto;
  text-align: center;
}

#printTable {
  table-layout: auto !important;
  width: 100% !important;
}
#printTable>>> .el-table__footer {
  width: 100% !important;
}
#printTable>>> .el-table__header-wrapper .el-table__header {
  width: 100% !important;
}

#printTable>>> .el-table__body-wrapper .el-table__body {
  width: 100% !important;
}
#printTable>>> .el-table__body-wrapper .el-table__footer-wrapper {
  width: 100% !important;
}

</style>


